import 'dart:math';
import '../database/app_database.dart';
import '../dao/user_dao.dart';
import '../entities/user_entity.dart';

class DatabaseService {
  static DatabaseService? _instance;
  AppDatabase? _database;
  UserDao? _userDao;

  DatabaseService._();

  static DatabaseService get instance {
    _instance ??= DatabaseService._();
    return _instance!;
  }

  // 初始化数据库
  Future<void> initDatabase() async {
    _database = await AppDatabase.getInstance();
    _userDao = _database!.userDao;
  }

  // 获取UserDao
  UserDao get userDao {
    if (_userDao == null) {
      throw Exception('Database not initialized. Call initDatabase() first.');
    }
    return _userDao!;
  }

  // 便捷方法：获取所有用户
  Future<List<User>> getAllUsers() async {
    return await userDao.getAllUsers();
  }

  // 便捷方法：观察所有用户变化
  Stream<List<User>> watchAllUsers() {
    return userDao.watchAllUsers();
  }

  // 便捷方法：批量插入用户
  Future<void> insertUsers(List<User> users) async {
    await userDao.insertUsers(users);
  }

  // 便捷方法：插入单个用户
  Future<void> insertUser(User user) async {
    await userDao.insertUser(user);
  }

  // 便捷方法：根据部门获取用户
  Future<List<User>> getUsersByDepartment(String department) async {
    return await userDao.getUsersByDepartment(department);
  }

  // 便捷方法：删除所有用户
  Future<void> deleteAllUsers() async {
    await userDao.deleteAllUsers();
  }

  // 批量更新用户
  Future<void> updateUsers(List<User> users) async {
    await userDao.updateUsers(users);
  }

  // 获取前三条用户
  Future<List<User>> getTopThreeUsers() async {
    return await userDao.getTopThreeUsers();
  }


  // 随机更新用户数据字段
  User updateUserRandomly(User user) {
    final random = Random();
    
    // 预定义的随机数据池
    final firstNames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '胡', '朱', '高', '林', '何', '郭', '马', '罗'];
    final lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞'];
    final cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都', '西安', '重庆', '天津', '苏州', '长沙', '郑州', '青岛', '大连', '宁波', '厦门', '福州', '沈阳'];
    final departments = ['技术部', '销售部', '市场部', '人事部', '财务部', '运营部', '产品部', '设计部', '客服部', '行政部'];
    final countries = ['中国', '美国', '日本', '韩国', '德国', '法国', '英国', '加拿大', '澳大利亚', '新加坡'];
    
    // 随机选择要更新的字段（0-8对应不同字段）
    final fieldToUpdate = random.nextInt(9);
    
    User updatedUser;
    switch (fieldToUpdate) {
      case 0: // 更新姓名
        final firstName = firstNames[random.nextInt(firstNames.length)];
        final lastName = lastNames[random.nextInt(lastNames.length)];
        updatedUser = user.copyWith(name: '$firstName$lastName');
        break;
      case 1: // 更新邮箱
        updatedUser = user.copyWith(email: 'updated${random.nextInt(9999)}@example.com');
        break;
      case 2: // 更新年龄
        updatedUser = user.copyWith(age: 18 + random.nextInt(48));
        break;
      case 3: // 更新电话
        updatedUser = user.copyWith(phone: '138${random.nextInt(100000000).toString().padLeft(8, '0')}');
        break;
      case 4: // 更新地址
        final city = cities[random.nextInt(cities.length)];
        updatedUser = user.copyWith(address: '$city${random.nextInt(999) + 1}号');
        break;
      case 5: // 更新城市
        updatedUser = user.copyWith(city: cities[random.nextInt(cities.length)]);
        break;
      case 6: // 更新国家
        updatedUser = user.copyWith(country: countries[random.nextInt(countries.length)]);
        break;
      case 7: // 更新薪资
        final salary = 3000 + random.nextInt(17001);
        updatedUser = user.copyWith(salary: salary);
        break;
      case 8: // 更新部门
        updatedUser = user.copyWith(department: departments[random.nextInt(departments.length)]);
        break;
      default:
        updatedUser = user;
    }
    return updatedUser;
  }

  // 生成5000条随机示例数据
  Future<void> insertSampleData() async {
    final random = Random();
    final sampleUsers = <User>[];
    
    // 预定义的随机数据池
    final firstNames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '胡', '朱', '高', '林', '何', '郭', '马', '罗'];
    final lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞'];
    final cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都', '西安', '重庆', '天津', '苏州', '长沙', '郑州', '青岛', '大连', '宁波', '厦门', '福州', '沈阳'];
    final districts = ['朝阳区', '海淀区', '西城区', '东城区', '丰台区', '石景山区', '浦东新区', '黄浦区', '静安区', '徐汇区', '长宁区', '普陀区', '天河区', '越秀区', '荔湾区', '海珠区', '白云区', '番禺区'];
    final departments = ['技术部', '销售部', '市场部', '人事部', '财务部', '运营部', '产品部', '设计部', '客服部', '行政部'];
    final countries = ['中国', '美国', '日本', '韩国', '德国', '法国', '英国', '加拿大', '澳大利亚', '新加坡'];
    
    for (int i = 0; i < 5000; i++) {
      final firstName = firstNames[random.nextInt(firstNames.length)];
      final lastName = lastNames[random.nextInt(lastNames.length)];
      final name = '$firstName$lastName';
      
      final city = cities[random.nextInt(cities.length)];
      final district = districts[random.nextInt(districts.length)];
      final country = countries[random.nextInt(countries.length)];
      final department = departments[random.nextInt(departments.length)];
      
      final age = 18 + random.nextInt(48); // 18-65岁
      final salary = 3000 + random.nextInt(17001); // 3000-20000薪资
      final phoneNumber = '138${random.nextInt(100000000).toString().padLeft(8, '0')}';
      
      final user = User(
        name: name,
        email: '${name.toLowerCase()}${i}@example.com',
        age: age,
        phone: phoneNumber,
        address: '$city$district${random.nextInt(999) + 1}号',
        city: city,
        country: country,
        salary: salary,
        department: department,
      );
      
      sampleUsers.add(user);
    }

    await insertUsers(sampleUsers);
  }

  // 关闭数据库
  Future<void> closeDatabase() async {
    await AppDatabase.closeDatabase();
    _database = null;
    _userDao = null;
  }
}